package com.orangelife.mobile.common.biz;
import java.util.Date;
import java.util.List;
import android.os.Handler;
import com.curry.android.adapter.FatherAdapter;
import com.markupartist.android.widget.PullToRefreshListView;
import com.markupartist.android.widget.PullToRefreshListView.IXListViewListener;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.constants.Constant;
public abstract class PullListViewImpl<T> extends OrangeLifeBaseActivity implements PullListViewRefreshOrLoad{
	/**
	 * 一页中数据的条数，初始设置为8条
	 */
	protected final int pageSize = 8;
	/**
	 * 初始页，初始化为第一页
	 */
	private int pageNo = Constant.PAGE_NO_DEFAULT;
	private int flags = 1;
	protected void setRefreshAndLoad(Boolean isRefresh,PullToRefreshListView pullToRefreshListView,FatherAdapter fatherAdapter){
		if(isRefresh){
			flags = 1;
			request(flags,1,pullToRefreshListView,fatherAdapter);
		}else{
			flags = 0;
			pageNo+=1;
			request(flags,pageNo++,pullToRefreshListView,fatherAdapter);
		}
	}

	private void request(int flags,int pageNo,PullToRefreshListView pullToRefreshListView,FatherAdapter fatherAdapter){
		requestList(flags,pageNo);
		onLoad(pullToRefreshListView);
		fatherAdapter.setList(listData());
		fatherAdapter.notifyDataSetChanged();
	}

	/**
	 * 刷新 拉下列表
	 *
	 * @param list
	 */
	protected void updateListView(List<List<T>> list,List<List<T>> mRefreshList,PullToRefreshListView pullToRefreshListView,FatherAdapter fatherAdapter) {
		if (list == null) {
			pullToRefreshListView.setPullLoadEnable(false);
			if (flags == 1) {
				mRefreshList.clear();
				fatherAdapter.setList(mRefreshList);
				fatherAdapter.notifyDataSetChanged();
			}
		}
		if (mRefreshList != null && list != null) {
			if (list.size() == 0) {
				fatherAdapter.setList(mRefreshList);
				fatherAdapter.notifyDataSetChanged();
				pullToRefreshListView.setPullLoadEnable(false);
			} else {
				if (flags == 1) {
					mRefreshList.clear();
				}
				pullToRefreshListView.setPullLoadEnable(true);
				mRefreshList.addAll(list);
				fatherAdapter.setList(mRefreshList);
				fatherAdapter.notifyDataSetChanged();
			}
		}
	}

	@Override
	public void pullListView(PullToRefreshListView lvList, final Handler mHandler) {
		lvList.setXListViewListener(new IXListViewListener() {
			@Override
			public void onRefresh() {
				mHandler.postDelayed(new Runnable() {
					@Override
					public void run() {
						refresh();
					}
				}, 2000);
			}

			@Override
			public void onLoadMore() {
				mHandler.postDelayed(new Runnable() {
					@Override
					public void run() {
						loadMore();
					}
				}, 2000);
			}
		});
	}
	
	 @Override
	 public void onLoad(PullToRefreshListView lvList) {
		lvList.stopRefresh();
		lvList.stopLoadMore();
		lvList.setRefreshTime(new Date().toLocaleString());
	 }

	@Override
	public void refresh() {}

	@Override
	public void loadMore(){}

	protected void requestList(int flags,int pageNo){}
	protected List<List<T>> listData(){return null;}
}
